package com.wxmit.ot.base.core;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxmit.ot.base.ApiResult;
import com.wxmit.ot.base.validate.AddGroup;
import com.wxmit.ot.base.validate.UpdateGroup;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;
import java.io.Serializable;
import java.util.List;


/**
 * OtBaseController
 *
 * @author huangxiong
 * @version V1.0
 * @date 2023/2/22 11:26
 */
public class OtBaseController<S extends OtBaseServiceImpl<?,T>,T,ID extends Serializable> {

    protected final S baseService;

    public OtBaseController(S baseService){
        this.baseService = baseService;
    }

    @GetMapping("/{id:\\d+}")
    public ApiResult<T> get(@PathVariable ID id){
        beforeGet(id);
        T domain = baseService.getById(id);
        afterGet(domain);
        return ApiResult.successWithData(domain);
    }

    @PostMapping("/list")
    public ApiResult<Page<T>> list(@RequestBody PageDTO<T> pageDTO){
        beforeList(pageDTO);
        Page<T> result = baseService.listPage(pageDTO);
        afterList(result);
        return ApiResult.successWithData(result);
    }

    @PostMapping
    public ApiResult add(@RequestBody @Validated({AddGroup.class, Default.class}) T domain){
        beforeAdd(domain);
        boolean result = baseService.save(domain);
        afterAdd(domain,result);
        return ApiResult.success();
    }

    @PutMapping
    public ApiResult update(@RequestBody @Validated({UpdateGroup.class, Default.class}) T domain){
        beforeUpdate(domain);
        boolean result = baseService.updateById(domain);
        afterUpdate(domain,result);
        return ApiResult.success();
    }

    @DeleteMapping("/{ids}")
    public ApiResult del(@PathVariable List<ID> ids){
        beforeDel(ids);
        boolean result = baseService.removeByIds(ids);
        afterDel(ids,result);
        return ApiResult.success();
    }

    protected void beforeGet(ID id){
        //DO NOTHING...
    }
    protected void afterGet(T domain){
        //DO NOTHING...
    }
    protected void beforeList(PageDTO<T> pageDTO){
        //DO NOTHING...
    }
    protected void afterList(Page<T> result){
        //DO NOTHING...
    }
    protected void beforeAdd(T domain){
        //DO NOTHING...
    }
    protected void afterAdd(T domain,boolean result){
        Assert.isTrue(result,"新增失败,请刷新后重试！");
    }
    protected void beforeUpdate(T domain){
        //DO NOTHING...
    }
    protected void afterUpdate(T domain,boolean result){
        Assert.isTrue(result,"更新失败,请刷新后重试！");
    }
    protected void beforeDel(List<ID> ids){
        //DO NOTHING...
    }
    protected void afterDel(List<ID> ids,boolean result){
        Assert.isTrue(result,"删除失败,请刷新后重试！");
    }
}
